package com.google.hackathon.geochallenge;

import android.location.Location;
import android.os.Parcel;
import android.os.Parcelable;

import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.LatLngBoundsCreator;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class Challenge implements Parcelable {

    private final List<Checkpoint> mCheckpoints;

    public Challenge() {
        mCheckpoints = new ArrayList<Checkpoint>();
    }

    public Challenge(Parcel in) {
        mCheckpoints = new ArrayList<Checkpoint>();
        in.readTypedList(mCheckpoints, Checkpoint.CREATOR);
    }

    public Challenge(JSONObject json) throws JSONException {
        mCheckpoints = new ArrayList<Checkpoint>();
        JSONArray jsonCheckpoints = json.getJSONArray("checkpoints");
        for (int i = 0; i < jsonCheckpoints.length(); ++i) {
            mCheckpoints.add(new Checkpoint(jsonCheckpoints.getJSONObject(i)));
        }
    }

    public List<Checkpoint> getCheckpoints() {
        return mCheckpoints;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel out, int flags) {
        out.writeTypedList(mCheckpoints);
    }

    public JSONObject toJSON() throws JSONException {
        JSONObject json = new JSONObject();

        JSONArray jsonCheckpoints = new JSONArray();
        for (Checkpoint checkpoint : mCheckpoints) {
            jsonCheckpoints.put(checkpoint.toJSON());
        }
        json.put("checkpoints", jsonCheckpoints);

        return json;
    }

    public LatLngBounds computeCameraView(LatLng currentLocation) {
        LatLngBounds.Builder boundsBuilder = LatLngBounds.builder().include(currentLocation);
        for (Checkpoint ckpt : mCheckpoints) {
            LatLng curLatLng = new LatLng(ckpt.getLatitude(), ckpt.getLongitude());
            boundsBuilder = boundsBuilder.include(curLatLng);
        }
        return boundsBuilder.build();
    }

    public static final Parcelable.Creator<Challenge> CREATOR
            = new Parcelable.Creator<Challenge>() {
        public Challenge createFromParcel(Parcel in) {
            return new Challenge(in);
        }

        public Challenge[] newArray(int size) {
            return new Challenge[size];
        }
    };
}
